package com.peanut.baby.mvp.main.expert.live;

import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import androidx.annotation.Nullable;
import androidx.viewpager.widget.ViewPager;

import com.peanut.baby.InitManager;
import com.peanut.baby.R;
import com.peanut.baby.comm.MyViewPagerAdapter;
import com.peanut.baby.http.ApiException;
import com.peanut.baby.model.Ad;
import com.peanut.baby.model.LiveRoom;
import com.peanut.baby.mvp.BaseMvpFragment;
import com.peanut.baby.mvp.bind.BindMobileActivity;
import com.peanut.baby.mvp.livedetail.LiveDetailActivity;
import com.peanut.baby.mvp.liveroom.LiveRoomActivity;
import com.peanut.baby.mvp.login.LoginActivity;
import com.peanut.baby.mvp.web.WebViewActivity;
import com.peanut.devlibrary.imageloader.ImageLoader;
import com.peanut.devlibrary.util.StringUtil;
import com.peanut.devlibrary.widget.pullrecycle.PullRecyclerView;
import com.peanut.devlibrary.widget.pullrecycle.layoutmanager.XLinearLayoutManager;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by anonymouslystudio on 2017/7/12.
 */

public class MainLiveListFragment extends BaseMvpFragment implements PullRecyclerView.OnRecyclerRefreshListener,
        MainLiveListContract.View,LiveRecyclerAdapter.OnItemViewClickListener,ViewPager.OnPageChangeListener{

    private static final String TAG = MainLiveListFragment.class.getSimpleName();
    @BindView(R.id.pull_recycler)
    PullRecyclerView pullRecyclerView;

    @BindView(R.id.banner_viewpager)
    ViewPager bannerViewpager;
    @BindView(R.id.banner_radiogroup)
    RadioGroup bannerRadiogroup;
    @BindView(R.id.banner_frame)
    FrameLayout bannerFrame;


    Unbinder unbinder;

    private int pageNo  = 1;
    private int pageCount = 5;

    protected MyViewPagerAdapter mAdAdapter;                      //banner适配器
    protected List<View> mAdViews;
    private Runnable scrollRunnable;
    private boolean resumed = false;
    private Handler handler = new Handler();


    private MainLiveListPresenter presenter;

    private LiveRecyclerAdapter adapter;
    private List<LiveRoom>  rooms;


    public String userId;
    public static MainLiveListFragment newInstance() {
        MainLiveListFragment fg = new MainLiveListFragment();

        return fg;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_expert_live, null);
        unbinder = ButterKnife.bind(this, rootView);

        pullRecyclerView.setOnRecyclerRefreshListener(this);
        return rootView;
    }

    @Override
    public void initData() {

        presenter = new MainLiveListPresenter(this,getActivity());


        scrollRunnable = new Runnable() {
            @Override
            public void run() {
                if (mAdAdapter != null && mAdAdapter.getCount() > 0) {
                    int currentIndex = bannerViewpager.getCurrentItem();
                    int pos = currentIndex + 1;
                    if (pos > mAdAdapter.getCount() - 1) {
                        pos = 0;
                    }

                    bannerViewpager.setCurrentItem(pos);
                }
                if (resumed) {
                    handler.postDelayed(scrollRunnable, 3000);
                }
            }
        };

        fixBannerSize();

        rooms = new ArrayList<>();
        adapter = new LiveRecyclerAdapter(getActivity(),rooms);
        adapter.setOnClickListener(this);
        pullRecyclerView.setLayoutManager(new XLinearLayoutManager(getActivity()));
        pullRecyclerView.setAdapter(adapter);

        pullRecyclerView.postRefreshing();
    }

    private void fixBannerSize(){
        //
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) bannerFrame.getLayoutParams();
        params.height = InitManager.getInstance().getScreenWidth() * 3 / 5;
        bannerFrame.setLayoutParams(params);
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


    @Override
    public void onLiveListGet(final List<LiveRoom> _rooms) {
        if(_rooms != null && !_rooms.isEmpty()){
            if(pageNo == 1){
                rooms.clear();
            }
            rooms.addAll(_rooms);
            adapter.notifyDataSetChanged();
            pullRecyclerView.enableLoadMore(_rooms.size() >= pageCount); // 当剩余还有大于0页的数据时，开启上拉加载更多
        }
        pullRecyclerView.stopRefresh();
        pullRecyclerView.stopLoadMore();
    }

    @Override
    public void onGetLiveListFailed(int pageNo, String error) {
        showToast(error);
        pullRecyclerView.stopRefresh();
        pullRecyclerView.stopLoadMore();
    }

    @Override
    public void onJoinSuccess(LiveRoom room) {
        dismissProgress();
        room.isEnroled = 1;
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onJoinFailed(String code,String reason) {
        dismissProgress();
        if(!ApiException.isApiException(code)){
            showToast(reason);
        }

    }

    @Override
    public void onBannerGet(boolean success, List<Ad> ads, String failReason) {
        initBanners(ads);
    }
    private void initBanners(final List<Ad> objs) {
        if (getActivity() != null) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (objs == null || objs.isEmpty()) {
                        fakeHideBanner();
                        return;
                    }
                    fixBannerSize();
                    if (mAdViews == null) {
                        mAdViews = new ArrayList<View>();
                    }
                    mAdViews.clear();
                    bannerRadiogroup.removeAllViews();
                    int size = objs.size();
                    int rightMargin = getActivity().getResources().getDimensionPixelSize(R.dimen.ad_radio_size);
                    for (int i = 0; i < size; i++) {
                        final Ad ad = objs.get(i);
                        final View adView = getActivity().getLayoutInflater().inflate(R.layout.layout_ad, null);
                        final ImageView img = (ImageView) adView.findViewById(R.id.ad_image);

                        ImageLoader.getInstance().loadImageView(getActivity(), ad.imgUrl, img);


                        mAdViews.add(adView);

                        adView.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                WebViewActivity.start(getActivity(), ad.htmlUrl, ad.name,ad.imgUrl);
                            }
                        });

                        RadioButton radioButton = new RadioButton(getActivity());
                        radioButton.setButtonDrawable(new ColorDrawable(Color.TRANSPARENT));
                        try {
                            radioButton.setBackgroundDrawable(getActivity().getResources().getDrawable(R.drawable.selector_ad_radiobutton));
                        } catch (Resources.NotFoundException e) {
                            e.printStackTrace();
                        }
                        RadioGroup.LayoutParams params = new RadioGroup.LayoutParams(rightMargin, rightMargin);
                        if (i != (size - 1)) {
                            params.rightMargin = rightMargin;
                        }
                        bannerRadiogroup.addView(radioButton, params);


                    }
                    ((RadioButton) bannerRadiogroup.getChildAt(0)).setChecked(true);
                    mAdAdapter = new MyViewPagerAdapter(mAdViews);
                    bannerViewpager.setAdapter(mAdAdapter);
                    bannerViewpager.setOnPageChangeListener(MainLiveListFragment.this);

                }
            });
        }
    }

    private void fakeHideBanner(){
        //
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) bannerFrame.getLayoutParams();
        params.height = 1;
        bannerFrame.setLayoutParams(params);
    }

    @Override
    public void onPullRefresh() {
        presenter.getBanner();
        pageNo = 1;
        presenter.getLiveList(pageNo,pageCount);
    }

    @Override
    public void onLoadMore() {
        pageNo += 1;
        presenter.getLiveList(pageNo,pageCount);
    }

    @Override
    public void onResume() {
        super.onResume();
        resumed = true;
        handler.postDelayed(scrollRunnable, 3000);

    }

    @Override
    public void onPause() {
        super.onPause();
        resumed = false;
        handler.removeCallbacks(scrollRunnable);


    }

    @Override
    public void onViewItemClicked(View v, LiveRoom room) {
        switch (v.getId()){
            case R.id.live_container:
                LiveDetailActivity.start(getActivity(),room.roomId);
                break;
            case R.id.live_join:
                if(InitManager.getInstance().getUser() == null){
                    LoginActivity.startForResult(getActivity());
                    return;
                }
                if(StringUtil.isNullOrEmpty(InitManager.getInstance().getUser().userToken)){
                    BindMobileActivity.startForResult(getActivity());
                    return;
                }

//                //3.1 added 如果不考虑报名状态 注释删掉
//                if(room.roomStatus == LiveRoom.ROOM_STATUS_FINISHED){
//                    LiveRoomActivity.start(getActivity(),room);
//                    return;
//                }

                if(InitManager.getInstance().getUserId().equals(room.expertId)
                        || InitManager.getInstance().getUserId().equals(room.serverId)){
                    LiveDetailActivity.start(getActivity(),room.roomId);
                }else{
                    if(room.isEnroled == 0){
                        showProgress("正在报名...",false);
                        presenter.joinRoom(room);
                    }else{
                        LiveRoomActivity.start(getActivity(),room);
                    }
                }

                break;
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        ((RadioButton) bannerRadiogroup.getChildAt(position)).setChecked(true);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
}
